import java.lang.Math;
import java.text.DecimalFormat;

public class Formulas
{      
    public Formulas()
    {
        
    }
    
    public double bondValue(double YTM, double time, double coupon, double faceValue)
    {
        double annuity = (coupon * (1 - (1/(Math.pow(1+ (YTM/100),time))))) / (YTM/100);
        double faceAmount = faceValue/(Math.pow(1+ (YTM/100),time));
        double totalValue= annuity + faceAmount;
        return roundThreeDecimals(totalValue);
    }
    
    public double semiAnnualBondValue(double YTM, double time, double coupon, double faceValue)
    {
        double annuity = ((coupon/2) * (1 - (1/(Math.pow(1+ ((YTM/100)/2),(time*2)))))) / ((YTM/100)/2);
        double faceAmount = faceValue/(Math.pow(1+ ((YTM/100)/2),(time*2)));
        double totalValue= annuity + faceAmount;
        return roundThreeDecimals(totalValue);
    }
    
    /**
     * PLEASE MAKE SURE THE "presentValue" IS A ROUNDED NUUMBER
     * EXAMPLE: 1080, INSTEAD OF 1080.43
     * OR ELSE IT WILL NOT WORK!
     */
    public void trialAndError(double time, double coupon, double presentValue)
    {
        double i = 0.10;
        while (i > 0) 
        {
            double newRateValue = Math.round((coupon * (1 - (1/ (Math.pow((1+ i),time)))) * (1/i)) + (1000 / (Math.pow((1+ i),time))));
            if(Math.round(newRateValue) == presentValue)
            {
            System.out.println("\n");    
            System.out.println("Interest Rate: " + i);
            }
            i = i - 0.00005;
        }
        if (i > (coupon / presentValue))
        {
            System.out.println("It's a Discount Bond");
        }
        else {
            System.out.println("It's a Premium Bond");
        }
    }

      private double roundThreeDecimals(double d) 
      {
          DecimalFormat threeDForm = new DecimalFormat("#.###");
          return Double.valueOf(threeDForm.format(d));
      }
    }
